<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;

class Netcity extends Common
{

	//列表
    public function index()
    {

        $sn = $this->request->get('sn');
        $title = $this->request->get('title');
        $system_title = $this->request->get('systemName');

        $this->assign(array('sn'=>$sn));
        $this->assign(array('title'=>$title));
        $this->assign(array('systemName'=>$system_title));
        $where = [];
        $where['isdel'] = 0;
        if($sn){
            $where['sn'] = $sn;
        }
        if($title){
            $where['title'] = ['like','%'.$title.'%'];
        }
        if($system_title){
            $where['id'] = ['exp','in(select groupid from cg_system where title like \'%'.$system_title.'%\')'];
        }
//        if($stuff){
//            //根据模糊查询规则把admin对应的id全部查询出来
//            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
//            $str = [];
//            foreach($ids as $k=>$v){
//                if($k==0)
//                    $str[] = " like '%\"$v[id]\"%' ";
//                else
//                    $str[] = " stuff like '%\"$v[id]\"%' ";
//            }
//            $str = implode('or',$str);
//
//            $where['stuff'] = array('exp',$str);
//        }

        $count = Db::table('cg_system_group')->where($where)->count();
        $data = Db::table('cg_system_group')->order("id desc")->where($where)->paginate(10,$count);
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();
         $maxpage=ceil($count/10);
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('maxpage',$maxpage);
        $this->assign('count',$count);
        return $this->fetch();
    }

    public function add(){

        if($_POST){

            $validate = new Valid([
                'sn'  => 'require|unique:cg_system_group',
                'title'  => 'require|unique:cg_system_group',
            ]);
            $data = [];
            $data['sn'] = $this->request->post('sn');
            $data['title'] = $this->request->post('title');
            $data['brief'] = $this->request->post('brief');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();

            $bool = Db::table('cg_system_group')->insert($data);
            if(false !== $bool){
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"添加成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"添加失败"
                ]);die;
            }

        }
        return $this->fetch('form');
    }

    /**
     * 修改
     * @return mixed
     * @throws \think\Exception
     */
    public function update(){
        $id = $this->request->param('id');

        if($_POST){
            $validate = new Valid([
                'sn'  => 'require|unique:cg_system_group',
                'title'  => 'require|unique:cg_system_group',
            ]);
            $data = [];
            $data['id'] = $id;
            $data['sn'] = $this->request->post('sn');
            $data['title'] = $this->request->post('title');
            $data['brief'] = $this->request->post('brief');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $bool = Db::table('cg_system_group')->where('id',$id)->update($data);
            if(false !== $bool){
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }
            die;
        }

        $data = Db::table('cg_system_group')->where('id',$id)->find();


        $this->assign('data',$data);
        $this->assign('id',$id);

        return $this->fetch('form');
    }

    /**
     * 维护系统
     * @return mixed
     * @throws \think\Exception
     */
    public function whSystem(){
        $id = $this->request->param('id');

        $data = Db::table('cg_system_group')->where('id',$id)->find();

        //查询没分组的系统
        $meifenzu = Db::table('cg_system')->field('id,title')->where('groupid',0)->select();
        $yifenzu = Db::table('cg_system')->field('id,title')->where('groupid','<>',0)->select();


        $this->assign('data',$data);
        $this->assign('meifenzu',$meifenzu);
        $this->assign('yifenzu',$yifenzu);
        $this->assign('id',$id);

        return $this->fetch();
    }

    //    批量设置分组
    public function batchSet(){
        $id = $this->request->post('id');
        $pid = $this->request->post('pid');
        if(!$id||!$pid){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['groupid'] = $pid;
        $bool = Db::table('cg_system')->where('id','in',$id)->update($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设置成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设置失败"
            ]);die;
        }
    }

    //    批量取消设置分组
    public function batchSet2(){
        $id = $this->request->post('id');
        $pid = $this->request->post('pid');
        if(!$id||!$pid){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['groupid'] = 0;
        $bool = Db::table('cg_system')->where('id','in',$id)->update($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设置成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设置失败"
            ]);die;
        }
    }


    /**
     * 删除
     * @throws \think\Exception
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_system_group')->where(array('id'=>$id))->update(['isdel'=>1]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }


    /**
     * 启用
     * @throws \think\Exception
     */
    public function qiyong(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_system_group')->where(array('id'=>$id))->update(['isdel'=>0]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }

    /**
     * 替换
     * @return mixed
     */
    public function tihuan(){
        $id = $this->request->param('id');
        if($_POST){;
            $new1 = $this->request->post('new1');
            $bool = Db::table('cg_system')->where('jxs',$id)->update(array('jxs'=>$new1));

            if(false!==$bool){
                $bool = Db::table('cg_system_jxs')->where(['jxs_id'=>$id,'system_id'=>$id])->update(array('jxs'=>$new1));

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"替换成功"
                ]);
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"替换失败"
                ]);
            }
            die;
        }


        $this->assign('id',$id);
        $sn = Db::table('cg_jxs')->where('id',$id)->value('sn');
        $this->assign('sn',$sn);
        $title = Db::table('cg_jxs')->where('id',$id)->value('title');
        $this->assign('title',$title);
        $yiyou = Db::table('cg_system')->where('jxs',$id)->select();
        $this->assign('yiyou',$yiyou);

        return $this->fetch();
    }

    /**
     * 追加
     * @return mixed
     */
    public function zhuijia(){
        return $this->fetch();
    }

    //选择经销商
    public function selectJXS(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //返回分区经销商树数据
    public function zonetreeajax(){
        $data = Db::table('cg_market_zoning')->where('isdel',0)->field('id,title')->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')->where(array('zoning'=>$v['id']))->field('id,title')->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')->where(array('provice'=>$vv['id']))->field('id,title')->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3['name'] = $v3['title'];
                    //查城市
                    $t3 = Db::table('cg_jxs')->where(array('city'=>$v3['id']))->field('id,title name')->select();//查经销商
                    $temp3['children'] = $t3;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    /**
     * 查询经销商的部分信息
     */
    public function findJxs(){
        $id = $this->request->post('id');
        $data = Db::table('cg_jxs')->where('id',$id)->field('sn,zoning,provice,city')->find();
        $data['city'] = Db::table('cg_market_city t')->join('employee t2','t2.id= t.head')->where('t.id',$data['city'])->value('t2.em_name');
        $data['provice'] = Db::table('cg_market_provice t')->join('employee t2','t2.id= t.head')->where('t.id',$data['provice'])->value('t2.em_name');
        $data['zoning'] = Db::table('cg_market_zoning t')->join('employee t2','t2.id= t.head')->where('t.id',$data['zoning'])->value('t2.em_name');
        echo json_encode($data);die;
    }

    /**
     * 返回经销桑json数据
     */
    public function provicejson(){
        //查询所有省份
        $data = Db::table('pro_products')->field('pro_name title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }


    /**
     * 替换经销商
     * @return mixed
     * @throws \think\Exception
     */
    public function repDealer(){
        if($_POST){
            $data = [];
            $data['zoning'] = $this->request->post('zoning');
            $data['provice'] = $this->request->post('provice');
            $data['city'] = $this->request->post('city');
            $data['jxs'] = $this->request->post('jxs');
            $id = $this->request->param('id');

            $validate = new Valid([
                'zoning'  => 'require',
                'provice'  => 'require',
                'city'  => 'require',
                'jxs'  => 'require',
            ]);


            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $old = Db::table('cg_system')->where('id',$id)->value('jxs');
            $bool = Db::table('cg_system')->where('id',$id)->update($data);
            if(false !== $bool){
                Db::table('cg_system_jxs')->where(['system_id'=>$id,'jxs_id'=>$old,'default'=>1])->update(['jxs_id'=>$data['jxs']]);
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"替换成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"替换失败"
                ]);die;
            }
        }
        $zoning = model('Zoning')->select();
        $this->assign('zoning',$zoning);
        return $this->fetch();
    }

    /**
     * 回收站
     * @return mixed
     */
    public function isdel()
    {

        $sn = $this->request->get('sn');
        $title = $this->request->get('title');
        $system_title = $this->request->get('systemName');

        $this->assign(array('sn'=>$sn));
        $this->assign(array('title'=>$title));
        $this->assign(array('systemName'=>$system_title));
        $where = [];
        $where['isdel'] = 1;
        if($sn){
            $where['sn'] = $sn;
        }
        if($title){
            $where['title'] = ['like','%'.$title.'%'];
        }
        if($system_title){
            $where['id'] = ['exp','in(select groupid from cg_system where title like \'%'.$system_title.'%\')'];
        }
//        if($stuff){
//            //根据模糊查询规则把admin对应的id全部查询出来
//            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
//            $str = [];
//            foreach($ids as $k=>$v){
//                if($k==0)
//                    $str[] = " like '%\"$v[id]\"%' ";
//                else
//                    $str[] = " stuff like '%\"$v[id]\"%' ";
//            }
//            $str = implode('or',$str);
//
//            $where['stuff'] = array('exp',$str);
//        }

        $count = Db::table('cg_system_group')->where($where)->count();
        $data = Db::table('cg_system_group')->order("id desc")->where($where)->paginate(10,$count);
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch();
    }


    //维护分组货号
    public function whproductAR(){
        $id = $this->request->param('id');
        $data = Db::table('cg_system_group')->where('id',$id)->find();
        $data['xitongshu'] = Db::table('cg_system')->where('groupid',$id)->count();
        $data['danpinshu'] = Db::table('cg_system_group_product')->where('groupid',$id)->count();
        $this->assign('data',$data);

        //查询分组下的产品列表
        $list = Db::table('cg_system_group_product t')->join('pro_products t2','t2.id=t.pro_id')->field('t.*,t2.pro_no,t2.pro_name')->where(['groupid'=>$id])->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    //增加产品
    public function addProduct(){
        $id = $this->request->post('id');
        $groupid = $this->request->post('groupid');

        //查询是否已存在
        $count = Db::table('cg_system_group_product')->where(['pro_id'=>$id,'groupid'=>$groupid])->count();
        if($count<=0){
            $bool = Db::table('cg_system_group_product')->insert(['pro_id'=>$id,'groupid'=>$groupid]);
            if(false !== $bool) {
                echo json_encode(['success' => true, 'msg' => 'ok']);
            }else{
                echo json_encode(['success' => false,'msg'=>'添加失败']);
            }
        }else{
            echo json_encode(['success' => false,'msg'=>'该产品已存在']);
        }

    }

    //删除产品
    public function delProduct(){
        $ids = $this->request->post('ids');

        //查询是否已存在
        if($ids!=''){
            $bool = Db::table('cg_system_group_product')->where('id','in',$ids)->delete();
            if(false !== $bool) {
                echo json_encode(['success' => true, 'msg' => 'ok']);
            }else{
                echo json_encode(['success' => false,'msg'=>'删除失败']);
            }
        }else{
            echo json_encode(['success' => false,'msg'=>'参数错误']);
        }

    }

    //批量删除系统分组到回收站
    public function batchDelete(){
        $ids = $this->request->post('ids');

        //查询是否已存在
        if($ids!=''){
            $bool = Db::table('cg_system_group')->where('id','in',$ids)->update(['isdel'=>1]);
            if(false !== $bool) {
                echo json_encode(['success' => true, 'msg' => 'ok']);
            }else{
                echo json_encode(['success' => false,'msg'=>'删除失败']);
            }
        }else{
            echo json_encode(['success' => false,'msg'=>'参数错误']);
        }

    }

    //保存货号
    public function savesn(){

        $ids = $this->request->post('sn/a');

        //查询是否已存在
        if($ids!=''){
            foreach($ids as $k=>$v){
                Db::table('cg_system_group_product')->where('id',$k)->update(['sn'=>$v]);
            }
            $bool = Db::table('cg_system_group_product')->where('id','in',$ids)->delete();
            echo json_encode(['success' => true, 'msg' => 'ok']);
        }else{
            echo json_encode(['success' => false,'msg'=>'参数错误']);
        }

    }
}
